package landlords.server.proxy;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import landlords.print.SimplePrinter;
import landlords.server.handler.WebSocketTransferHandler;

import java.net.InetSocketAddress;

public class WebSocketProxy implements Proxy{
    @Override
    public void start(int port) throws InterruptedException {
        EventLoopGroup group= Epoll.isAvailable()?new EpollEventLoopGroup():new NioEventLoopGroup();
        ServerBootstrap bootstrap=new ServerBootstrap()
                .group(group)
                .channel(Epoll.isAvailable()? EpollServerSocketChannel.class: NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch){
                        ch.pipeline()
                                .addLast(new WebSocketTransferHandler());
                    }
                });
        ChannelFuture f=bootstrap.bind().sync();
        SimplePrinter.serverLog("Websocket服务器已启动");

    }
}
